const { Admin } = require('../model/admin')
const {User} = require('../model/user')
const bcrypt = require('bcrypt')
const {Level} = require('../model/level')
const {Topic} = require('../model/topics')
const {getUserLever,getRootPath,getMaterialSrc} = require('../utils')
const moment= require('moment-timezone')
//管理员登录
exports.login = async (req, res, next) => {
    try {
        const validValue = req.validValue
        let user = await Admin.findOne({
            username: validValue.username
        }).select("+password")
        if (!user) {
            return res.status(200).json({
                code: 400,
                msg: '登录失败，该用户名可能未注册'
            })
        }
        let isRight = await bcrypt.compare(validValue.password, user.password)
        if (!isRight) {
            return res.status(200).json({
                code: 400,
                msg: '用户名或密码错误'
            })
        }
        let userinfo = await Admin.findOne({
            _id: user._id
        }).populate('avatar')
        res.status(200).json({
            code: 200,
            msg: '登录成功',
            data: {
                token: user.generateToken(),
                userInfo: userinfo
            }
        })
    } catch(err){
        next(err)
    }
}
//获取所有用户
exports.getUserList = async (req, res, next) => {
    try {
        let userList = await User.find().select("+gender +phone +status")
        .populate({
            path:'avatar'
        })
        if (!userList) {
            return res.status(400).json({
                code: 400,
                msg: '查询用户列表失败'
            })
        }
        res.status(200).json({
            code: 200,
            msg: '用户列表查询成功',
            data: {
                userList
            }
        })
    } catch (err) {
        next(err)
    }
}
//获取指定用户
exports.getUser = async (req, res, next) => {
    try {
        let userId = req.params.id
        let user = await User.findById(userId).select("+gender +phone +status").populate({
            path:'avatar'
        })

        if (!user) return res.status(400).json({
            code: 400,
            msg: '用户不存在'
        })
        res.status(200).json({
            code: 200,
            msg: '查询指定用户成功',
            data: user
        })
    } catch (err) {
        //通过错误处理中间件处理错误
        next(err)
    }
}
//修改指定用户
exports.updateUser = async (req, res, next) => {
    try {
        let userId = req.params.id
        let body = req.body
        if(body.password){
            const salt = await bcrypt.genSalt(10)
            body.password = await bcrypt.hash(body.password, salt)
        }
       

        const data = await User.findByIdAndUpdate(userId, body)

        // res.send('修改用户')
        if (!data) return res.status(400).json({
            code: 400,
            msg: '更新用户失败'
        })
        let updatedUser = await User.findById(data._id)
        res.status(200).json({
            code: 200,
            msg: '更新用户成功',
            data:updatedUser
        })
    } catch (err) {
        //通过错误处理中间件处理错误
        next(err)
    }
}
//删除指定用户
exports.delUser = async (req, res, next) => {
    try {
        let userId = req.params.id
        //查询ID然后删除
        const data = await User.findByIdAndDelete(userId)
        if (!data) return res.status(400).json({
            code: 400,
            msg: '删除用户失败,用户可能不存在',
            value: {
                _id: userId
            }
        })
        const body = req.body
        res.status(200).json({
            code: 200,
            msg: '删除用户成功',
            data: data._id
        })
    } catch (err) {
        next(err)
    }
}

//获取帖子列表
exports.getTopicList = async (req, res, next) => {
    try {
        //分页：获取当前页数
        let page = Math.max(req.query.page - 0, 1) - 1
        //设置每页条数
        const { per_page = 10 } = req.query
        let perpage = Math.max(req.query.per_page * 1, 1)
        let userVote = []
        let userCollect=[]
        if(req.loginuser){
            const loginuser = await User.findById(req.loginuser._id).select("+likingTopics +collectingTopics")
            userVote = loginuser.likingTopics
            userCollect = loginuser.collectingTopics
        }
        //设置关键词正则，i为不区分大小写
        let keyword = new RegExp(req.query.keyword,'i')
        let cate = new RegExp(req.query.cate,'i') 
        let topicsList = await Topic.find({
            $or:[
                {
                    title: {
                        $regex: keyword
                    }
                },
                {
                    text:{
                        $regex: keyword
                    }
                },
            ],
            cate:{
                $regex:cate
            }
        })
        .populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        }).sort({createdAt :-1})
        if (!topicsList) return res.status(200).json({
            code: 400,
            msg: '获取帖子列表失败'
        })
        topicsList:await Promise.all(topicsList.map(async (item,index,array) => {
            if(item.user.experience){
                let levelNum= getUserLever(item.user.experience)
                let {level,url} =await Level.findOne({level:levelNum})
                item.user._doc["level"] = {
                    level:level,
                    url:url
                }
            } else {
                item.user._doc["level"] = {
                    level:'unknown',
                    url:`/level/level1.png`
                }
            }
            if(userVote.includes(item._id)){
                item._doc.isVote=true
            } else {
                item._doc.isVote=false
            }
            if(userCollect.includes(item._id )){
                item._doc.isCollected=true
            } else {
                item._doc.isCollected=false
            }

            return item
        }))
        res.status(200).json({
            code: 200,
            msg: '获取贴子列表成功',
            data: topicsList
        })
    } catch (err) {
        next(err)
    }
}
//获取待审核帖子
exports.getCheckTopics = async (req,res,next)=>{
    try{
        const topicList = await Topic.find({status:0})
        if (!topicList){
            return res.status(200).json({
                code:400,
                msg:"获取列表失败"
            })
        }
        res.status(200).json({
            code:400,
            msg:"获取列表成功",
            data:topicList
        })
    } catch(err){
        next(err)
    }
}
//获取指定帖子
exports.getTopic = async (req, res, next) => {
    try {
        const { fields = "" } = req.query
        //字段过滤
        // const selectFields = fields.split(';').filter(f => f).map(f => " +" + f).join("")
        const topic = await Topic.findById(req.params.id).populate({
            path:"images user",
            select:"+experience",
            populate: {
                path:"avatar",
                strictPopulate:false
            }
        })
        if (!topic) return res.status(200).json({
            code: 400,
            msg: '帖子不存在'
        })
        if(topic.user.experience){
            let levelNum= getUserLever(topic.user.experience)
            let {level,url} =await Level.findOne({level:levelNum})
            topic.user._doc["level"] = {
                level:level,
                url:url
            }
        } else {
            topic.user._doc["level"] = {
                level:'unknown',
                url:`/level/level1.png`
            }
        }
        let follower = await User.find({ following: topic.user._id })
        const fansList = []
        follower.forEach((item,index,array)=>{
            fansList.push(item._id)
        })
        topic.user._doc["fansList"] = fansList
        
        res.status(200).json({
            code: 200,
            msg: '获取帖子成功',
            data: topic
        })
    } catch (err) {
        next(err)
    }
}
// exports.createTopic = async (req, res, next) => {
//     try {
//         let imgArr = req.body.imgArr
//         if (!imgArr || imgArr.length == 0) {
//             let images = []
//             let topic = new Topic({ ...req.body, user: req.userData._id, images: images, createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') })
//             await topic.save()
//             await User.findByIdAndUpdate(req.userData._id, { $inc: { experience: +6 } })
//             res.status(200).json({
//                 code: 200,
//                 msg: '帖子发布成功',
//                 data: topic
//             })
//         } else {
//             let images = []
//             let imageId = ''
//             let returnImg = []
//             const p = new Promise((resolve, reject) => {
//                 imgArr.forEach(async (item, index, arr) => {
//                     let nameStr = item.replace(/^https?:\/\/[^\/]*/mg,'')
//                     let uid = nameStr.split('/')[2]
//                     let imgName = nameStr.split('/')[3]
//                     //在已经上传的图片数据库中查询发布帖子时拥有的图片
//                     //移动上传的图片
//                     try{
//                         fs.moveSync(`${rootPath}/public/uploads/${uid}/${imgName}`, `${rootPath}/public/uploads/${imgName}`)
//                         console.log('success')
//                     } catch(err){
//                         return reject()
//                     }
//                     const restu = await postImg.findOne({ name: imgName })
//                     //更改数据库中图片的url
//                     postImg.findByIdAndUpdate(restu.id, { url: `/uploads/${imgName}` }, () => { })
//                     images.push(restu._id)
//                     returnImg.push(`/uploads/${restu.name}`)
//                     if (arr.length==images.length) {
//                         imageId = uid
//                         resolve()
//                     }
//                 });
//             })

//             p.then(async () => { 
//                 let content = req.body.content
//                 let a = new RegExp(`/${imageId}`,'g')
//                 req.body.content = content.replace(a, '')
//                 req.body.imgArr = returnImg
//                 const topic = new Topic({ 
//                     ...req.body,
//                     user: req.userData._id,
//                     images: images,
//                     createdAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
//                 })

//                 await topic.save()
//                 await User.findByIdAndUpdate(req.userData._id, { $inc: { experience: +6 } })
//                 res.status(200).json({
//                     code: 200,
//                     msg: '帖子发布成功,经验+6',
//                     data: topic
//                 })
//                 try{
//                     fs.removeSync(`${rootPath}/public/uploads/${imageId}/`)
//                     console.log('remove success')
//                 } catch(err){
//                     console.error(err);
//                 }
//             },()=>{
//                 return res.status(400).json({
//                     code:400,
//                     msg:'上传图片失败'
//                 })
//             })
//         }
//     } catch (err) {
//         next(err)
//     }
// }
//更新帖子
exports.updateTopic = async (req, res, next) => {
    try {
        //
        let imgArr = req.body.imgArr
        // console.log(imgArr)
        if (!imgArr || imgArr.length == 0) {
            //帖子的图片组
            let images = []
            //帖子ID
            let topicId = req.params.id
            const data = await Topic.findByIdAndUpdate(topicId, {
                content:req.body.content,
                title:req.body.title,
                cate:req.body.cate,
                images: images,
                imgArr:imgArr,
                updatedAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
            }).select("+updatedAt")
            let updatedTopic = await Topic.findById(topicId)
            if(!data) {
                return res.status(200).json({
                    code: 200,
                    msg: '编辑帖子失败1',
                    data: data
                })
            }
            res.status(200).json({
                code: 200,
                msg: '编辑帖子成功',
                data: updatedTopic
            })
        } else {
            let topicId = req.params.id
            //帖子图片组
            let images = []
            //存储图片ID
            let imageId = ''
            //返回的图片
            let returnImg = []
            const p = new Promise(async (resolve, reject) => {
                //前端发送图片循环
                await Promise.all(imgArr.map(async (item, index, arr) => {
                    //切割帖子图片的字符串获取信息 
                    let nameStr = item.replace(/^https?:\/\/[^\/]*/mg,'')
                    let uid=''
                    let imgName =''
                    if(nameStr.split('/').length==4){
                        uid = nameStr.split('/')[2]
                        imgName = nameStr.split('/')[3]
                        //移动上传的图片
                        try{
                            fs.moveSync(`${rootPath}/public/uploads/${uid}/${imgName}`, `${rootPath}/public/uploads/${imgName}`)
                            // console.log(`${rootPath}/public/uploads/${uid}/${imgName}`)
                        } catch(err){
                            console.log(err)
                        }
                        //更改数据库中图片的url
                        const restu = await postImg.findOne({name: imgName })
                        if (restu){
                            await postImg.findByIdAndUpdate(restu.id, { url: `/uploads/${imgName}` })
                            // postImg.findByIdAndUpdate(res.id, { topic: topic._id }, () => { })
                            images.push(restu._id)
                            returnImg.push(`/uploads/${restu.name}`)
                        } else {
                            return reject()
                        }
                    }
                    if(nameStr.split('/').length==3){
                        imgName = nameStr.split('/')[2]
                        const restu = await postImg.findOne({name: imgName })
                        if(restu){
                            await postImg.findByIdAndUpdate(restu._id, { url: `/uploads/${imgName}` })
                            // await postImg.findByIdAndUpdate(restu._id, { topic: topic._id })
                            images.push(restu._id)
                            returnImg.push(`/uploads/${restu.name}`)
                            uid=restu.user
                        }
                    }
                    if ( arr.length==images.length) {
                        imageId = uid
                        resolve()
                    }
                    return item
                }));
            })
            p.then(async () => { 
                let content = req.body.content
                if(imageId.length!=0){
                    let a = new RegExp(`/${imageId}`,'g')
                    req.body.content = content.replace(a, '')
                }
                req.body.imgArr = returnImg
                const data = await Topic.findByIdAndUpdate(topicId, {
                    content:req.body.content,
                    title:req.body.title,
                    cate:req.body.cate,
                    images: images,
                    imgArr:imgArr,
                    updatedAt:moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss') 
                }).select("+updatedAt")
                if(!data){
                    return res.status(200).json({
                        code: 200,
                        msg: '编辑帖子失败2',
                        data: data
                    })
                }
                res.status(200).json({
                    code: 200,
                    msg: '编辑帖子成功',
                    data: topic
                })
            },()=>{ 
                return res.status(200).json({
                    code:400,
                    msg:"图片出错，请删除错误图片重新修改"
                })
            })
        }
    } catch (err) {
        next(err)
    }
}
//删除帖子
exports.deleteTopic = async (req, res, next) => {
    try {
        const data = await Topic.findByIdAndRemove(req.params.id)
        console.log(data)
        if (!data) return res.status(200).json({
            code: 400,
            msg: '删除帖子失败',
        })

        res.status(200).json({
            code: 200,
            msg: '删除帖子成功',
            data: data
        })
    } catch (err) {
        next(err)
    }
}